package com.hospicpc.demos.controller;

import com.hospicpc.demos.commom.Result;
import com.hospicpc.demos.entity.UserInfo;
import com.hospicpc.demos.service.Impl.MessagesServiceImpl;
import com.hospicpc.demos.service.Impl.UserInfoServiceImpl;
import com.hospicpc.demos.websocket.WebSocket;
import com.hospicpc.demos.websocket.pojo.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import static com.hospicpc.demos.utils.JwtUtil.getUserIdByJWT;
import static com.hospicpc.demos.websocket.WebSocket.webSockets;

@Slf4j
@RestController
@RequestMapping("/SendMessage")
@RabbitListener(queues = "DirectQueue")//监听的队列名称 DirectQueue
public class SendMessageController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    UserInfoServiceImpl userInfoService;

    @Autowired
    HttpServletRequest httpServletRequest;

    @Autowired
    private MessagesServiceImpl messagesService;

    /**
     * @param id   发送给谁的id
     * @param text 发送的内容
     * @return {@link String}
     */
    @GetMapping("/sendDirectMessage/{userId}")
    public Result sendDirectMessage(@RequestParam String id, @RequestParam String text) {
        String messageId = id;
        String messageData = text;
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String token = httpServletRequest.getHeader("Authorization");
        UserInfoController userInfoController = new UserInfoController();
        Integer UserId =getUserIdByJWT(httpServletRequest);
        log.info("发送消息用户：{}", UserId);
        UserInfo nickNameByUserId = userInfoService.getNickNameByUserId(UserId);
        String nickName = nickNameByUserId.getNickName();
        log.info("发送消息用户昵称：{}", nickName);
        Map<String, String> map = new HashMap<>();
        map.put("messageId", messageId);
        map.put("messageData", messageData);
        map.put("createTime", createTime);
        map.put("nickName", nickName);
        messagesService.insertMessage(UserId,messageId,messageData,createTime,nickName);
        if (WebSocket.isUserOnline(messageId)) {
            // 用户在线，直接通过WebSocket发送消息
            WebSocket webSocket = webSockets.stream()
                    .filter(ws -> messageId.equals(ws.userId))
                    .findFirst()
                    .orElse(null);
            if (webSocket != null) {
                webSocket.sendOneMessage(messageId, messageData,createTime,nickName);
            }
            log.info("发送消息用户：{}", UserId);
            Message message = new Message();
            message.setMessage(messageData);
            message.setCreateTime(createTime);
            message.setFromName(nickName);
            return Result.success(message);
        }
        else {
            // 用户不在线，将消息发送到RabbitMQ
            rabbitTemplate.convertAndSend("DirectExchange", "DirectRouting", map);
            Message message = new Message();
            message.setMessage(messageData);
            message.setCreateTime(createTime);
            message.setFromName(nickName);
            return Result.success(message);
        }
    }

}
